﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsReferralTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// Referral Business Object
    /// </summary>

    public class Referral : BOBase
    {
        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected Referral() { }

        #endregion

        #region Public Properties

        #region Instance Properties


        /// <summary>
        /// UserID.
        /// </summary>
        public int UserID
        {
            get { return _userID; }
            set
            {
                if (_userID != value)
                {
                    if (OnPropertyChanging("UserID", _userID, value))
                    {
                        int oldValue = _userID;
                        _userID = value;
                        OnPropertyChanged("UserID", oldValue, value);
                    }
                }
            }
        }  private int _userID = -1;


        /// <summary>
        /// FriendName.
        /// </summary>
        public string FriendName
        {
            get { return _friendName; }
            set
            {
                if (_friendName != value)
                {
                    if (OnPropertyChanging("FriendName", _friendName, value))
                    {
                        string oldValue = _friendName;
                        _friendName = value;
                        OnPropertyChanged("FriendName", oldValue, value);
                    }
                }
            }
        }  private string _friendName = null;


        /// <summary>
        /// FriendEmailAddress.
        /// </summary>
        public string FriendEmailAddress
        {
            get { return _friendEmailAddress; }
            set
            {
                if (_friendEmailAddress != value)
                {
                    if (OnPropertyChanging("FriendEmailAddress", _friendEmailAddress, value))
                    {
                        string oldValue = _friendEmailAddress;
                        _friendEmailAddress = value;
                        OnPropertyChanged("FriendEmailAddress", oldValue, value);
                    }
                }
            }
        }  private string _friendEmailAddress = null;


        /// <summary>
        /// MessageText.
        /// </summary>
        public string MessageText
        {
            get { return _messageText; }
            set
            {
                if (_messageText != value)
                {
                    if (OnPropertyChanging("MessageText", _messageText, value))
                    {
                        string oldValue = _messageText;
                        _messageText = value;
                        OnPropertyChanged("MessageText", oldValue, value);
                    }
                }
            }
        }  private string _messageText = null;


        
        /// <summary>
        /// Date/time at which the Referral was created.
        /// </summary>
        public DateTime? ReferredDate
        {
            get { return _referredDate; }
            set
            {
                if (_referredDate != value)
                {
                    if (OnPropertyChanging("ReferredDate", _referredDate, value))
                    {
                        DateTime? oldValue = _referredDate;
                        _referredDate = value;
                        OnPropertyChanged("ReferredDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _referredDate = null;

        /// <summary>
        /// Status.
        /// </summary>
        public string Status
        {
            get { return _status; }
            set
            {
                if (_status != value)
                {
                    if (OnPropertyChanging("Status", _status, value))
                    {
                        string oldValue = _status;
                        _status = value;
                        OnPropertyChanged("Status", oldValue, value);
                    }
                }
            }
        }  private string _status = null;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty Referral object.
        /// </summary>
        public static Referral CreateNew()
        {
            Referral obj = new Referral();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.ReferredDate = DateTime.Now;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static Referral CreateNew(ReferralCollection collection)
        {
            Referral obj = CreateNew();
            collection.Add(obj);
            return (obj);
        }

        #endregion

        #region GetAllReferral

        /// <summary>
        /// Returns a collection of Referral.
        /// </summary>
        public static ReferralCollection GetAllReferral(int userid)
        {
            ReferralTableAdapter adapter = new ReferralTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsReferral.ReferralDataTable tbl = adapter.GetData(userid);

            ReferralCollection list = new ReferralCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsReferral.ReferralRow row in tbl.Rows)
                {
                    Referral referral = new Referral();
                    RelationalToObject(referral, row);
                    list.Add(referral);
                }
            }

            return (list);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified Referral.
        /// </summary>
        public static void Update(Referral obj)
        {
            bool updateReferral = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateReferral = (obj.ObjState != ObjectState.Unchanged);

                if (!updateReferral)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsReferral.ReferralDataTable tbl = null;
            if (updateReferral)
            {
                ReferralTableAdapter adapter = new ReferralTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();


                tbl = new dsReferral.ReferralDataTable();
                dsReferral.ReferralRow row = tbl.NewReferralRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("UserID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("Referral: UserID={0}, FriendEmailAddress={1}, {2}", UserID, FriendEmailAddress));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more SubAdmin objects.
    /// </summary>

    public class ReferralCollection : List<Referral>
    {
        #region Types

        public class UserComparer : IComparer<Referral>
        {
            public int Compare(Referral r1, Referral r2)
            {
                return (String.Compare(r1.FriendEmailAddress, r2.FriendEmailAddress));
            }
        }

        #endregion

        #region Public Methods

        #region FindByUserID

        public Referral FindByUserID(int userid)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].UserID == userid)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion

    }
}
